package com.hp.bon.sgw.wh.channel.auth;

import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alipay.api.internal.util.StringUtils;
import com.hp.bon.sgw.wh.channel.common.BizConsts;
import com.hp.bon.sgw.wh.channel.common.BizParam;
import com.hp.bon.sgw.wh.channel.common.BizResult;
import com.hp.bon.sgw.wh.channel.groupConsistency.utils.HttpClientUtils;
import com.hp.bon.sgw.wh.service.UserResourceConfigService;

public class ServAuthService {

	private static final Logger _log = LoggerFactory.getLogger(ServAuthService.class);

	public static ServAuthService servAuthService;

	public static synchronized ServAuthService instance() {
		if (null == servAuthService) {
			servAuthService = new ServAuthService();
		}
		return servAuthService;
	}

	public BizResult doAuthService(BizParam bizParam) {

		BizResult bizResult = new BizResult();
		bizResult.setCode(BizConsts.STATUS_ACOUNT_API_SUCCESS);

		String apiUrl = bizParam.getParamString(BizConsts.KEY_ACCOUNT_API_URL);
		if (StringUtils.isEmpty(apiUrl)) {
			apiUrl = UserResourceConfigService.getValue("Api_getServAuthInfo");
		}
		_log.info("Auth apiUrl={}", apiUrl);
		String doDemo = UserResourceConfigService.getValue("Api_getServAuthInfo_Demo");
		if ("true".equalsIgnoreCase(doDemo)) {
			Map<String, Object> demoBodyMap = new HashMap<String, Object>();
			demoBodyMap.put("resultCode", "0");
			demoBodyMap.put("resultMsg", "0");
			demoBodyMap.put("acctId", Long.valueOf("100180891307"));
			demoBodyMap.put("prodInstId", "100149222115");

			demoBodyMap.put("areaCode", "027");
			demoBodyMap.put("regionId", "1001");
			demoBodyMap.put("paymentFlag", Long.valueOf("0"));
			demoBodyMap.put("statusCd", "FOA");

			bizResult.setHttpBody(JSON.toJSONString(demoBodyMap));
			return bizResult;
		}
		try {
			String jsonBody = JSONObject.toJSONString(bizParam.getParams());
			String reposeBody = HttpClientUtils.postHttpStr(jsonBody, apiUrl);
			bizResult.setHttpBody(reposeBody);
		} catch (Exception e) {
			_log.error(e.getMessage(), e);
			bizResult.setCode(BizConsts.STATUS_ACOUNT_API_FAIL);
		}
		return bizResult;
	}

}
